package logic

import (
	"context"

	"wxapi/internal/services"
	"wxapi/internal/svc"
	"wxapi/internal/types"

	"gitee.com/dromara/carbon/v2"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetDoctorIdleTimeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetDoctorIdleTimeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDoctorIdleTimeLogic {
	return &GetDoctorIdleTimeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetDoctorIdleTimeLogic) GetDoctorIdleTime(req *types.GetDoctorIdleTimeReq) (resp *types.GetDoctorIdleTimeResp, err error) {
	today := carbon.ParseByFormat(req.Date, "Y-m-d")

	times, err := services.GetDoctorWorkTime(l.ctx, l.svcCtx, req.DoctorID)
	if err != nil {
		return nil, err
	}

	orderItems, err := services.GetOrderItemsByItems(l.ctx, l.svcCtx, req.DoctorID, today)
	if err != nil {
		return nil, err
	}

	type workTime struct {
		BeginTime carbon.Carbon
		EndTime   carbon.Carbon
	}
	workTimes := make([]workTime, 0)
	for _, item := range orderItems {
		workTimes = append(workTimes, workTime{
			BeginTime: item.BeginTime,
			EndTime:   item.BeginTime.AddMinutes(int(item.Duration) * int(item.Count)),
		})
	}

	resp = &types.GetDoctorIdleTimeResp{
		Time: make([]types.DoctorIdleTime, 0),
	}
	for _, time := range times {
		item := types.DoctorIdleTime{
			Time: time,
		}
		for _, workTime := range workTimes {
			if item.Time >= workTime.BeginTime.Format("H:i") && item.Time <= workTime.EndTime.Format("H:i") {
				item.IsBusy = true
				break
			}
		}
		resp.Time = append(resp.Time, item)
	}
	return
}
